package com.k2data.k2app.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.k2data.k2app.common.ResponseConstant;
import com.k2data.k2app.exception.K2ResponseException;
import lombok.extern.log4j.Log4j2;

import java.util.*;

/**
 *
 * Created by clb on 17-4-5.
 */
@Log4j2
public class JsonUtils {
	/**
	 * 将json转化成map
	 * @param jsonStr
	 * @return
	 */
	public static Map<String, Object> convertJsonStrToMap(Object jsonStr)  throws K2ResponseException{
		if(jsonStr == null){
			return new HashMap<>();
		}
		if(StringUtils.isEmpty(jsonStr.toString())){
			return new HashMap<>();
		}
		try{
			Map<String, Object> map = JSON.parseObject(
					jsonStr.toString(),new TypeReference<Map<String, Object>>(){} );
			return map;
		}catch (Exception e){
			throw new K2ResponseException(ResponseConstant.GENERAL,
					String.format("%s",ResponseConstant.JSON_PARSE_ERROR));
		}
	}

	/**
	 * 将json转化成list
	 * @param jsonStr
	 * @return
	 */
	public static List convertJsonStrToList(Object jsonStr){
		Optional<Object> optional = Optional.ofNullable(jsonStr);
		List list = new ArrayList();
		if(optional.isPresent()){
			if(!StringUtils.isEmpty(jsonStr.toString())&&jsonStr.toString().startsWith("[")&&jsonStr.toString().endsWith("]")){
				list = JSON.parseArray(jsonStr.toString());
			}
		}
		return list;
	}
}
